from selenium.webdriver.common.by import By
from traceback import print_exc
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
"""
减少冗余的代码，操作步骤（page页面）、元素（loctor）、执行（testcases）都是分开的
拆开、解耦，都是分开的
"""
class Base:
    def __init__(self,driver):
        self.driver = driver
        # 选择元素的字典
        self.loctor = {
            "id":By.ID,
            "name":By.NAME,
            "class name":By.CLASS_NAME,
            "xpath":By.XPATH,
            "css":By.CSS_SELECTOR,
            "link text":By.LINK_TEXT,
            "tag name":By.TAG_NAME,
            "partial link text":By.PARTIAL_LINK_TEXT
        }
    #自己封装一个查找元素的方法
    def find_element(self,loc_method,loc):
        """
        :param loc_method: 传入要操作的定位方式：xpath、id、name、class name
        :param loc: 具体元素的值
        :return:
        """
        try:
            return WebDriverWait(self.driver,10,0.5).until(EC.presence_of_element_located((self.loctor[loc_method],loc)))
        except:
            print_exc()
            return "元素超时，没有找到"
    # 查找一组的元素
    def find_elements(self,loc_method,loc,num):
        """
        :param loc_method: 要传入定位方式
        :param loc: 具体元素的值
        :param num: 要操作第几个
        :return:
        """
        try:
            return WebDriverWait(self.driver,10,0.5).until(EC.presence_of_all_elements_located((self.loctor[loc_method],loc)))[num]
        except:
            print_exc()
            return "元素超时，没有找到"
    # 点击
    def click_ele(self,loc_method,loc):
        self.find_element(loc_method,loc).click()

    # 点击一组元素方法
    def click_eles(self,loc_method,loc,num):
        self.find_elements(loc_method,loc,num).click()

    # 输入内容
    def input_text(self,loc_method,loc,text):
        ele = self.find_element(loc_method,loc)
        # 先清空，再输入
        ele.clear()
        ele.send_keys(text)

    # 输入一组的内容
    def input_texts(self,loc_method,loc,num,text):
        ele = self.find_elements(loc_method,loc,num)
        # 先清空
        ele.clear()
        ele.send_keys(text)

    # 句柄切换
    def win_(self,num):
        win = self.driver.window_handles
        self.driver.switch_to.window(win[num])

    # 返回文本内容
    def get_content(self,loc_method,loc):
        text = self.find_element(loc_method,loc).text
        return text




















